﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_NovaAdmin.Web.Core.ServiceExtensions
{
    /// <summary>
    /// 添加Json读取配置
    /// </summary>
    public static class ConfigOptionSetup
    {
        private static readonly MethodInfo ConfigureOptionMethod = typeof(ConfigOptionSetup)
            .GetMethod(nameof(ConfigureOption), BindingFlags.Static | BindingFlags.NonPublic)!;

        /// <summary>
        /// 自动注册所有标记了 ConfigSectionAttribute 的配置项
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <exception cref="InvalidOperationException"></exception>
        public static void AddConfigOptions(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            ArgumentNullException.ThrowIfNull(services);
            ArgumentNullException.ThrowIfNull(configuration);
            var processedSections = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            // 获取当前程序集所有的类型
            var types = Assembly.GetExecutingAssembly().GetTypes();
            // 过滤出所有标记了 ConfigSectionAttribute 的类
            IEnumerable<(Type Type, ConfigSectionAttribute Attribute)> list = types
                .Where(t => t.IsClass && !t.IsAbstract)
                .Select(t => (Type: t, Attribute: t.GetCustomAttribute<ConfigSectionAttribute>()))
                .Where(x => x.Attribute != null)!;

            foreach (var (type, attribute) in list)
            {
                if (string.IsNullOrWhiteSpace(attribute.SectionName))
                {
                    throw new InvalidOperationException(
                        $"类型 {type.FullName} 的 ConfigSectionAttribute 必须指定 SectionName");
                }

                if (!processedSections.Add(attribute.SectionName))
                {
                    throw new InvalidOperationException(
                        $"重复的配置节名称: {attribute.SectionName} (类型: {type.FullName})");
                }

                RegisterConfiguration(services, configuration, type, attribute.SectionName);
            }
        }

        /// <summary>
        /// 通过反射动态调用ConfigureOption方法以注册给定配置类型的选项到服务容器中
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="optionsType"></param>
        /// <param name="sectionName"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private static void RegisterConfiguration(
            IServiceCollection services,
            IConfiguration configuration,
            Type optionsType,
            string sectionName)
        {
            try
            {
                var genericMethod = ConfigureOptionMethod.MakeGenericMethod(optionsType);
                genericMethod.Invoke(null, new object[] { services, configuration, sectionName });
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                    $"配置类型 {optionsType.FullName} 注册失败", ex);
            }
        }

        /// <summary>
        /// 将配置节绑定到 TOptions 类型，依赖注入可使用 TOptions 类型的配置
        /// </summary>
        /// <typeparam name="TOptions"></typeparam>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="sectionName"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private static void ConfigureOption<TOptions>(
            IServiceCollection services,
            IConfiguration configuration,
            string sectionName) where TOptions : class, new()
        {
            var section = configuration.GetSection(sectionName);
            if (!section.Exists())
            {
                throw new InvalidOperationException(
                    $"配置节 {sectionName} 未找到，请检查配置文件");
            }

            services.Configure<TOptions>(section);
        }
    }
}
